<template>
  <div>
    <el-card>
      <div class="ly-tree-container">
        <el-col :span="14">
          <el-tree
            default-expand-all
            :data="allData"
            :expand-on-click-node="false"
            :render-content="render"
            @node-click="handleNodeClick"
          ></el-tree>
        </el-col>
        <el-col :span="10">
          <el-descriptions
            class="margin-top"
            title="节点信息"
            :column="1"
            border
            :model="nodeInfo"
            style="position: fixed; width: 35%"
          >
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-help"></i>
                节点名称
              </template>
              <el-tag size="small">{{ nodeInfo.partName }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-operation"></i>
                节点层级
              </template>
              <el-tag size="small" type="success">
                {{ nodeInfo.partLevel }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-operation"></i>
                排序层级
              </template>
              <el-tag size="small" type="success">
                {{ nodeInfo.sort }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item>
              <template slot="label">
                <i class="el-icon-s-flag"></i>
                是否为叶节点
              </template>
              <el-tag
                size="small"
                :type="nodeInfo.isLeaf ? 'danger' : 'success'"
              >
                {{ nodeInfo.isLeaf }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item
              v-if="
                nodeInfo.partAttributeVO != null &&
                nodeInfo.partAttributeVO.dataTypes != null
              "
            >
              <template slot="label">
                <i class="el-icon-s-cooperation"></i>
                绑定功能
              </template>
              <div
                v-for="(tag, i) in nodeInfo.partAttributeVO.dataTypes"
                :key="i"
              >
                <el-col :span="8">
                  <el-tag size="small" type="success">
                    {{
                      tag == 'addProgress'
                        ? '进度'
                        : tag == 'addQuality'
                        ? '质量'
                        : '安全'
                    }}
                  </el-tag>
                </el-col>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </div>
    </el-card>
    <el-dialog
      :title="nodeTitle"
      :visible.sync="centerDialogVisible"
      width="40%"
      center
      @close="
        () => {
          centerDialogVisible = false
          resetForm()
        }
      "
    >
      <el-form
        ref="houseInfoForm"
        :model="nodeFormData"
        size="medium"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="节点名称">
          <el-input v-model.trim="nodeFormData.newPartName"></el-input>
        </el-form-item>
        <el-form-item label="排序层级">
          <el-input-number
            v-model.trim="nodeFormData.sort"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否为叶节点">
          <el-radio-group v-model.trim="nodeFormData.newIsLeaf" size="medium">
            <el-radio
              v-for="(item, index) in newIsLeafOptions"
              :key="index"
              :label="item.value"
              :disabled="opType == 'edit'"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="支持绑定功能">
          <el-checkbox-group v-model="nodeFormData.partAttributeVO.dataTypes">
            <el-checkbox label="addProgress">进度</el-checkbox>
            <el-checkbox label="addQuality">质量</el-checkbox>
            <el-checkbox label="addSecurity">安全</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注：">
          若设为叶子节点，该节点下不可添加子项
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="
            () => {
              centerDialogVisible = false
              resetForm()
            }
          "
        >
          取 消
        </el-button>
        <el-button v-if="opType == 'add'" type="primary" @click="addNode">
          确 定
        </el-button>
        <el-button v-if="opType == 'edit'" type="primary" @click="editNode">
          修 改
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  import { uuid } from '@/utils/index'
  export default {
    name: 'MapTree',
    props: {
      data: { type: Array, default: () => [] },
      usual_drop: Array,
      end_drop: Array,
      root_drops: Array,
      delete_node: Function,
      rename: Function,
      add_node: Function,
    },
    data() {
      return {
        opType: '',
        nodeTitle: '',
        nodeFormData: {
          newPartName: '',
          newIsLeaf: false,
          sort: 0,
          partAttributeVO: { dataTypes: [] },
        },
        newIsLeafOptions: [
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ],
        allData: [],
        currentId: '',
        currenContent: '',
        centerDialogVisible: false,
        node: {
          parentId: '',
          partName: '',
          isLeaf: false,
          partLevel: 1,
          sort: 1,
          parentId: '',
        },
        nodeInfo: {
          isLeaf: '',
          partName: '',
          partLevel: '',
          partAttributeVO: { dataTypes: [] },
        },
      }
    },
    watch: {
      data() {
        this.transformData()
      },
    },
    mounted() {
      this.transformData()
    },
    created() {},

    methods: {
      handleNodeClick(data) {
        this.nodeInfo = data
        console.log(data)
      },
      resetForm() {
        this.nodeFormData = {
          newPartName: '',
          newIsLeaf: false,
          sort: 0,
          partAttributeVO: { dataTypes: [] },
        }
      },
      addNode() {
        if (this.nodeFormData.newPartName == '') {
          this.$baseMessage('请输入新节点名称!', 'warning')
          return
        }
        // if (condition) {
        // }
        if (this.nodeFormData.partAttributeVO.dataTypes.length == 0) {
          console.log('未绑定功能')
          this.$baseMessage('未绑定功能!', 'warning')
          this.nodeFormData.partAttributeVO.dataTypes = []
          return
        } else {
          console.log(this.nodeFormData.partAttributeVO)
          // return
        }
        let list = _.cloneDeep(this.data)
        this.node.partName = this.nodeFormData.newPartName
        this.node.isLeaf = this.nodeFormData.newIsLeaf
        this.node.sort = this.nodeFormData.sort
        this.node.partAttributeVO = this.nodeFormData.partAttributeVO
        //调用add API
        if (this.add_node) {
          this.add_node(this.node).then(() => {
            list.push(this.node)
            this.$message({
              type: 'success',
              message: '添加成功!',
            })
            // this.$emit('update:data', list)
            this.$baseEventBus.$emit('reload-router-view')
            this.resetForm()
          })
        }
      },
      cancel() {
        this.currentId = ''
      },
      editNode(data) {
        if (this.nodeFormData.newPartName == '') {
          this.$baseMessage('请输入节点名称!', 'warning')
          return
        }
        if (this.nodeFormData.partAttributeVO.dataTypes.length == 0) {
          this.$baseMessage('未绑定功能!', 'warning')
          this.nodeFormData.partAttributeVO.dataTypes = []
          return
        } else {
          console.log(this.nodeFormData.partAttributeVO)
          // return
        }
        let list = _.cloneDeep(this.data)
        // let item = list.find((l) => l.partId == data.partId)
        // item.partName = this.currenContent
        this.node.partName = this.nodeFormData.newPartName
        this.node.isLeaf = this.nodeFormData.newIsLeaf
        this.node.sort = this.nodeFormData.sort
        this.node.partAttributeVO = this.nodeFormData.partAttributeVO
        if (this.rename) {
          this.rename(this.node).then(() => {
            this.$emit('update:data', list)
            this.$message({
              type: 'success',
              message: '修改成功!',
            })
            this.$baseEventBus.$emit('reload-router-view')
            this.resetForm()
          })
        }
      },
      handleInput(v) {
        this.currenContent = v
      },
      //后台删除后，前端数据同步更新
      remove(id) {
        let list = _.cloneDeep(this.data)
        list = list.filter((l) => l.partId != id)
        this.$emit('update:data', list)
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
      },
      handleRemove(data) {
        this.$confirm(`此操作将永久删除 ${data.partName}, 是否继续?`, '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            //调用删除API
            if (this.delete_node) {
              this.delete_node(data.partId).then(() => {
                this.remove(data.partId)
              })
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      handleRename(data) {
        // console.log(data)
        this.nodeTitle = '修改节点'
        this.opType = 'edit'
        this.nodeFormData.newIsLeaf = data.isLeaf
        this.nodeFormData.newPartName = data.partName
        if (data.partAttributeVO == null) {
        } else {
          this.nodeFormData.partAttributeVO = data.partAttributeVO
        }
        this.nodeFormData.sort = data.sort
        this.centerDialogVisible = true
        this.node = data
        // this.currenContent = data.partName
        // this.currentId = data.partId
      },
      //添加选择项节点
      handleAddCheckPoint(data) {
        this.nodeTitle = '添加新节点'
        this.opType = 'add'
        this.node.parentId = data.partId
        this.node.partId = uuid(32)
        this.node.partLevel = data.partLevel + 1
        this.node.sort = 1
        this.centerDialogVisible = true
      },
      handleCommand(data, value) {
        console.log(value)
        if (value === 'addCheckPoint') {
          this.handleAddCheckPoint(data)
        } else if (value === 'rename') {
          this.handleRename(data)
        } else if (value === 'rm') {
          this.handleRemove(data)
        }
      },
      render(h, { node, data, store }) {
        let list =
          data.partLevel === 5
            ? this.end_drop
            : data.partLevel === 1
            ? this.root_drops
            : data.partLevel === 0
            ? []
            : this.usual_drop

        return (
          <div style={{ with: '100%' }}>
            {data.partLevel === 1 ? (
              <i class="el-icon-office-building"></i>
            ) : data.partLevel === 2 ? (
              <i class="el-icon-school"></i>
            ) : data.partLevel === 3 ? (
              <i class="el-icon-c-scale-to-original"></i>
            ) : data.partLevel === 4 ? (
              <i class="el-icon-document-copy"></i>
            ) : (
              <i class="el-icon-suitcase"></i>
            )}
            {data.partId === this.currentId ? (
              <el-input
                value={this.currenContent}
                on-input={this.handleInput}
                class="rename"
              ></el-input>
            ) : (
              data.partName
            )}
            {data.partId !== this.currentId ? (
              <el-dropdown
                placement="bottom-start"
                trigger="click"
                on-command={this.handleCommand.bind(this, data)}
              >
                <span class="el-dropdown-link">
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  {list.map((item) => (
                    <el-dropdown-item command={item.op}>
                      {item.value}
                    </el-dropdown-item>
                  ))}
                </el-dropdown-menu>
              </el-dropdown>
            ) : (
              <span style="float:'right'">
                <el-button
                  type="text"
                  on-click={this.editNode.bind(this, data)}
                >
                  确认
                </el-button>
                <el-button type="text" on-click={this.cancel}>
                  取消
                </el-button>
              </span>
            )}
          </div>
        )
      },
      transformData() {
        let AllData = _.cloneDeep(this.data)
        // console.log(AllData)
        let _ss = []
        for (let index = 0; index < AllData.length; index++) {
          if (AllData[index].partLevel == 0) {
            _ss.push(AllData[index])
          }
        }
        console.log(_ss)
        //   isLeaf: false, parentId: '',partId: '0',partLevel: 0, partName: 'NO1',sort: 0,
        let treeMapList = AllData.reduce((memo, current) => {
          memo[current['partId']] = current
          return memo
        }, {})
        let treeData = AllData.reduce((array, current) => {
          let parentId = current.parentId
          let partLevel = current.partLevel
          let parent = treeMapList[parentId]
          if (partLevel == 0) {
            //根元素
            array.push(current)
          } else if (parent) {
            parent.children
              ? parent.children.push(current)
              : (parent.children = [current])
          }
          return array
        }, [])
        this.allData = treeData
        // console.log(treeData)
      },
    },
  }
</script>

<style lang="scss" scoped>
  .el-tree {
    width: 100%;
    .el-dropdown {
      float: right;
    }
    .el-tree-node_content {
      height: 32px;
    }
    // .el-input.el-input--small {
    //   // width: 50%;

    //   .el-input__inner {
    //     width: 1000px;
    //     z-index: 999;
    //   }
    // }
  }
</style>
